//
//  SJLabelViewController.m
//  WSL
//
//  Created by CJ on 2018/3/26.
//  Copyright © 2018年 sanjuetech. All rights reserved.
//

#import "SJLabelViewController.h"
#import "SJLabelCell.h"
#import "SJClassListApi.h"
#import "SJLabelItem.h"

@interface SJLabelViewController () <UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) int page;

@property (strong, nonatomic) UIButton *doneButton;
@property (nonatomic, strong) NSMutableArray *selectedArray;

@end

@implementation SJLabelViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupUI];
    
    [self loadNewData];
}

- (void)setupUI {
    
    self.view.backgroundColor = SJColorHexString(@"#00000099");
    
    UILabel *label = [UILabel new];
    label.numberOfLines = 1;
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:SJLayoutFrame(14)];
    label.text = @"标签选择：（最多可选择3个标签）";
    
    [self.view addSubview:label];
    label.sd_layout
    .leftSpaceToView(self.view, SJLayoutFrame(20))
    .topSpaceToView(self.view, SJLayoutFrame(200))
    .heightIs(SJLayoutFrame(14))
    .widthIs(SJScreenW - SJLayoutFrame(40));
    
    [self.view addSubview:self.collectionView];
    self.collectionView.sd_layout
    .leftSpaceToView(self.view, SJLayoutFrame(20))
    .topSpaceToView(label, SJLayoutFrame(20))
    .heightIs(SJLayoutFrame(180))
    .widthIs(SJScreenW - SJLayoutFrame(40));
    
    [self.view addSubview:self.doneButton];
    self.doneButton.sd_layout
    .heightIs(SJLayoutFrame(40))
    .widthIs(SJLayoutFrame(335))
    .centerXEqualToView(self.view)
    .topSpaceToView(self.collectionView, SJLayoutFrame(22));
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self.view removeFromSuperview];
    [self removeFromParentViewController];
}

#pragma mark - getter

- (UIButton *)doneButton {
    
    if (!_doneButton) {
        
        _doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _doneButton.sd_cornerRadius = @(SJCornerRadius);
        _doneButton.backgroundColor = SJColorHexString(@"#99c7ff");
        [_doneButton setTitle:@"完 成" forState:UIControlStateNormal];
        [_doneButton setTitleColor:SJColorHexString(@"#ffffff") forState:UIControlStateNormal];
        [_doneButton addTarget:self action:@selector(doneAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _doneButton;
}

- (void)doneAction {
    
    if (self.selectedArray.count > 3 ) {
        
        NSString *msg = @"最多可选择3个标签";
        [SVProgressHUD showErrorWithStatus:msg];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    if (self.selectedArray.count == 0 ) {
        
        NSString *msg = @"请选择标签";
        [SVProgressHUD showErrorWithStatus:msg];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    
    if (self.doneBlock) {
        
        self.doneBlock(self.selectedArray);
        
        [self.view removeFromSuperview];
        [self removeFromParentViewController];
    }
    
}

- (NSMutableArray *)dataArray {
    
    if (!_dataArray) {
        
        _dataArray = [[NSMutableArray alloc] init];
        
    }
    return _dataArray;
}

- (NSMutableArray *)selectedArray {
    
    if (!_selectedArray) {
        
        _selectedArray = [[NSMutableArray alloc] init];
        
    }
    return _selectedArray;
}

- (UICollectionView *)collectionView {
    
    if (!_collectionView) {
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat h = SJLayoutFrame(30);
        CGFloat w = SJLayoutFrame(60);
        layout.minimumInteritemSpacing = SJLayoutFrame(30);
        layout.minimumLineSpacing = SJLayoutFrame(7);
        layout.itemSize = CGSizeMake(w, h);
        
        _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor clearColor];
        
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.allowsMultipleSelection = YES;
        
        [_collectionView registerClass:[SJLabelCell class] forCellWithReuseIdentifier:NSStringFromClass([SJLabelCell class])];
        
    }
    
    return _collectionView;
}


#pragma mark - UICollectionViewDataSource, UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SJLabelCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([SJLabelCell class]) forIndexPath:indexPath];
    
    SJLabelItem *item = self.dataArray[indexPath.row];
    
    cell.item = item;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [self selectedOrDeselectedItemAtIndexPath:indexPath];
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
    [self selectedOrDeselectedItemAtIndexPath:indexPath];
}

- (void)selectedOrDeselectedItemAtIndexPath:(NSIndexPath*)indexPath {
    
    SJLabelItem *item = self.dataArray[indexPath.row];
    item.isSelected = !item.isSelected;
    [_collectionView reloadItemsAtIndexPaths:@[indexPath]];
    if (item.isSelected) {
        if (![self.selectedArray containsObject:item]) {
            [self.selectedArray addObject:item];
        }
    } else {
        if ([self.selectedArray containsObject:item]) {
            [self.selectedArray removeObject:item];
        };
    }
}

#pragma mark - request

- (void)loadNewData {
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"rn"] = SJCountOfPage;
    parameters[@"pn"] = @"0";
    
    SJClassListApi *api = [[SJClassListApi alloc] initWithParameters:parameters];
    
    if ([api loadCacheWithError:nil]) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            self.dataArray = [[NSArray modelArrayWithClass:[SJLabelItem class] json:api.responseObject[@"content"][@"data"]] mutableCopy];
        }
        
        [self.collectionView reloadData];
    }
    
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            self.dataArray = [[NSArray modelArrayWithClass:[SJLabelItem class] json:api.responseObject[@"content"][@"data"]] mutableCopy];
            
        }
        
        [self.collectionView reloadData];
        
    } failure:^(YTKBaseRequest *request) {
        [self.collectionView reloadData];
    }];
    
}


@end
